package SwingContainer;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Window01Class extends JFrame {
    //添加标签控件
    JLabel label = new JLabel("这是一个标签控件");
    //添加一个复选框
    JCheckBox agreeField=new JCheckBox("选中我按钮三才会启用");
    public Window01Class(String title) {
        super(title);
        //添加根panel类
        JPanel root_panel = new JPanel();
        //将panel加入窗口里
        this.setContentPane(root_panel);
        //添加按钮对象
        JButton button1 = new JButton("按钮1");
        JButton button2 = new JButton("测试按钮2");
        JButton button3=new JButton("修改文本框内容");
        //将按钮对象加入到panel对象当中
        root_panel.add(button1);
        root_panel.add(button2);
        root_panel.add(button3);
        //将标签控件加入到根panel
        root_panel.add(label);
        //简化添加控件写法
        root_panel.add(new JLabel("简化写法2"));
        //添加按钮事件以及简写方法,按钮1的写法则为lambda表达式,按钮2则为匿名内部类写法
//        MyActionListener listener =new MyActionListener();
//        button1.addActionListener(listener);
        button1.addActionListener((e)->{
            System.out.println("按钮1被点击");
        });

        button2.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                showTime();
            }
        });


        //添加文本框对象
        JTextField textField=new JTextField(20);
        root_panel.add(textField);

        //文本框事件
        button3.addActionListener((e)->{
            textField.setText("你点击了一个按钮");
        });


        root_panel.add(agreeField);
        //设置复选框为未选中
        agreeField.setSelected(false);
        //设置按钮3为禁用状态
        button3.setEnabled(false);
        //添加复选框和按钮3联动效果
        agreeField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(agreeField.isSelected()){
                    button3.setEnabled(true);
                    textField.setText("复选框选中");
                    textField.setEnabled(true);
                }else {
                    button3.setEnabled(false);
                    textField.setText("未选中");
                    textField.setEnabled(false);
                }
            }
        });

    }
    private void showTime(){
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:mm");
        String timeStr = sdf.format(new Date());
//            System.out.println(timeStr);
        label.setText(timeStr);
    }
}
